package com.mall.controller;

import com.alibaba.fastjson2.JSON;
import com.mall.common.es.SkuEsModel;
import com.mall.common.utils.R;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.io.IOException;
import java.util.List;

@RestController
public class EsSearchController {


    @Autowired
    private RestHighLevelClient restClient;

    @PostMapping("/search/save/product")
    R saveProductIndex(@RequestBody List<SkuEsModel> skuEsModelList){
        BulkRequest bulkRequest = new BulkRequest();
        for(SkuEsModel skuEsModel : skuEsModelList){
            IndexRequest indexRequest = new IndexRequest("product");
            indexRequest.id(skuEsModel.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(skuEsModel), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        try {

            BulkResponse bulkResponse =  restClient.bulk(bulkRequest,RequestOptions.DEFAULT);
            if(!bulkResponse.hasFailures()){
                return R.ok();
            }else{
                return R.error();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
